﻿/*
 * Created by SharpDevelop.
 * User: lebeda
 * Date: 17.2.2014
 * Time: 7:31
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;

using System.IO;
using System.Text.RegularExpressions;

using System.Xml.Serialization;

namespace simpleExplorer.menuProviderImpl
{
    /// <summary>
    /// Description of filesystemMenuProvider.
    /// </summary>
    public class XmlMenuProvider: MenuItemProvider
    {
        private MenuItem selfMenuItem;
        
        Dictionary<string, MenuItem> menuIndex;
        
        public XmlMenuProvider(MenuItem aMenuItem)
        {
            this.selfMenuItem = aMenuItem;
            menuIndex = new Dictionary<string, MenuItem>();
            
            
            foreach (MenuItem menuItem in DeserializeListFromXML(aMenuItem.cmd)) {
                // TODO - include type items
                menuItem.menuUp = selfMenuItem;
                menuIndex[menuItem.caption] = menuItem;
            }
            
        }
        
        public List<MenuItem> GetMenuItemList(string filter) {
            List<MenuItem> result = new List<MenuItem>(menuIndex.Count);
            
            foreach (MenuItem menuItem in menuIndex.Values) {
                string caption = menuItem.caption;
                if (!String.IsNullOrWhiteSpace(filter)) {
                    string smallCaption = caption.ToLower();
                    string smallFind = filter.ToLower();
                    if (smallCaption.Contains(smallFind)) {
                        result.Add(menuItem);
                    }
                } else {
                    result.Add(menuItem);
                }
            }
            
            return result;
        }
        
        public MenuItem GetCommandByMenuItem(string caption) {
            return menuIndex[caption];
        }
        
        public  MenuItem GetSelfMenuCreateDefinition() {
            return this.selfMenuItem;
        }
        
        static List<MenuItem> DeserializeListFromXML(string file)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<MenuItem>));
            TextReader textReader = new StreamReader(file);
            List<MenuItem> menus;
            menus = (List<MenuItem>)deserializer.Deserialize(textReader);
            textReader.Close();

            return menus;
        }

    }
}
